package club.zhilin.guli.service.vod.service.impl;

import club.zhilin.guli.common.base.result.CommonResultCodeEnum;
import club.zhilin.guli.service.base.exception.GlobalException;
import club.zhilin.guli.service.vod.config.VodProperties;
import club.zhilin.guli.service.vod.service.IVideoService;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * @author zhilin
 * @since 2022/2/11 20:46
 */
@Service
@EnableConfigurationProperties({VodProperties.class})
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class VideoServiceImpl implements IVideoService {

    private final VodProperties vodProperties;
    private final DefaultAcsClient client;

    @Override
    public String uploadVideo(InputStream inputStream, String originalFileName) {
        UploadStreamRequest request = new UploadStreamRequest(vodProperties.getKeyId(), vodProperties.getKeySecret(), originalFileName.substring(0, originalFileName.lastIndexOf(".")), originalFileName, inputStream);
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        String videoId = response.getVideoId();
        if (StringUtils.isEmpty(videoId)) {
            throw new GlobalException(CommonResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR);
        }
        return videoId;
    }

    @Override
    public DeleteVideoResponse removeVideo(String ids) throws ClientException {
        DeleteVideoRequest request = new DeleteVideoRequest();
        request.setVideoIds(ids);
        return client.getAcsResponse(request);
    }

    @Override
    public String getPlayAuth(String id) throws ClientException {
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(id);
        GetVideoPlayAuthResponse response = client.getAcsResponse(request);
        return response.getPlayAuth();
    }
}
